//
//  KooCalendarFlowLayout.m
//  KooIEDUCalendarDemo
//
//  Created by nowcoder on 2024.
//

#import "KooCalendarFlowLayout.h"
#import "KooCalendarConfig.h"

@implementation KooCalendarFlowLayout

#pragma mark - Initialization

- (instancetype)init {
    return [self initWithConfig:[KooCalendarConfig defaultConfig]];
}

- (instancetype)initWithConfig:(KooCalendarConfig *)config {
    self = [super init];
    if (self) {
        self.calendarConfig = config;
        [self setupDefaultLayout];
    }
    return self;
}

#pragma mark - Setup

- (void)setupDefaultLayout {
    // 设置为横向滚动布局（用于月份切换）
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    // 启用分页效果
    self.minimumLineSpacing = 0;
    self.minimumInteritemSpacing = self.calendarConfig.cellSpacing.width;
    self.sectionInset = UIEdgeInsetsZero;
    
    // 设置默认的item大小
    self.itemSize = self.calendarConfig.cellSize;
}

#pragma mark - Public Methods

- (void)updateWithConfig:(KooCalendarConfig *)config {
    self.calendarConfig = config;
    [self setupDefaultLayout];
    [self invalidateLayout];
}

#pragma mark - Layout Override Methods

- (void)prepareLayout {
    [super prepareLayout];
    
    // 确保布局参数是最新的
    if (self.calendarConfig) {
        self.minimumInteritemSpacing = self.calendarConfig.cellSpacing.width;
        self.itemSize = [self calculatedCellSize];
    }
}

- (CGSize)collectionViewContentSize {
    if (!self.collectionView) {
        return CGSizeZero;
    }
    
    // 计算总内容大小：页数 × 页面宽度
    NSInteger numberOfSections = [self.collectionView numberOfSections];
    CGFloat pageWidth = CGRectGetWidth(self.collectionView.bounds);
    CGFloat totalWidth = numberOfSections * pageWidth;
    CGFloat totalHeight = CGRectGetHeight(self.collectionView.bounds);
    
    return CGSizeMake(totalWidth, totalHeight);
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *attributes = [[NSMutableArray alloc] init];
    
    if (!self.collectionView) {
        return attributes;
    }
    
    // 计算需要显示的section范围
    CGFloat pageWidth = CGRectGetWidth(self.collectionView.bounds);
    NSInteger numberOfSections = [self.collectionView numberOfSections];
    
    NSInteger startSection = MAX(0, (NSInteger)(CGRectGetMinX(rect) / pageWidth));
    NSInteger endSection = MIN(numberOfSections - 1, (NSInteger)(CGRectGetMaxX(rect) / pageWidth));
    
    // 为每个section中的items创建布局属性
    for (NSInteger section = startSection; section <= endSection; section++) {
        NSInteger numberOfItems = [self.collectionView numberOfItemsInSection:section];
        
        for (NSInteger item = 0; item < numberOfItems; item++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:section];
            UICollectionViewLayoutAttributes *itemAttributes = [self layoutAttributesForItemAtIndexPath:indexPath];
            if (itemAttributes) {
                [attributes addObject:itemAttributes];
            }
        }
    }
    
    return attributes;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    if (!self.collectionView) {
        return attributes;
    }
    
    // 计算cell的位置
    CGSize cellSize = [self calculatedCellSize];
    CGFloat pageWidth = CGRectGetWidth(self.collectionView.bounds);
    
    // 计算在7x6网格中的位置
    NSInteger row = indexPath.item / 7;  // 行号（0-5）
    NSInteger col = indexPath.item % 7;  // 列号（0-6）
    
    // 计算section的x偏移量（用于分页）
    CGFloat sectionOffsetX = indexPath.section * pageWidth;
    
    // 计算item在当前页面内的位置
    CGFloat itemX = col * (cellSize.width + self.calendarConfig.cellSpacing.width);
    CGFloat itemY = row * (cellSize.height + self.calendarConfig.cellSpacing.height);
    
    // 设置最终位置
    attributes.frame = CGRectMake(sectionOffsetX + itemX, itemY, cellSize.width, cellSize.height);
    
    return attributes;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    // 当bounds发生变化时（比如屏幕旋转），需要重新计算布局
    return !CGRectEqualToRect(newBounds, self.collectionView.bounds);
}

#pragma mark - Helper Methods

- (CGSize)calculatedCellSize {
    if (!self.collectionView) {
        return self.calendarConfig.cellSize;
    }
    
    CGFloat totalWidth = CGRectGetWidth(self.collectionView.bounds);
    CGFloat totalHeight = CGRectGetHeight(self.collectionView.bounds);
    
    if (totalWidth <= 0 || totalHeight <= 0) {
        return self.calendarConfig.cellSize;
    }
    
    // 计算单个Cell的宽度：总宽度减去6个间距，再除以7列
    CGFloat cellWidth = (totalWidth - 6 * self.calendarConfig.cellSpacing.width) / 7.0;
    
    // 计算单个Cell的高度：总高度减去5个行间距，再除以6行
    CGFloat cellHeight = (totalHeight - 5 * self.calendarConfig.cellSpacing.height) / 6.0;
    
    // 如果配置中指定了固定高度，使用配置值
    if (self.calendarConfig.cellSize.height > 0) {
        cellHeight = MIN(cellHeight, self.calendarConfig.cellSize.height);
    }
    
    // 如果原配置是正方形，保持正方形
    if (self.calendarConfig.cellSize.width == self.calendarConfig.cellSize.height) {
        cellHeight = cellWidth;
    }
    
    return CGSizeMake(cellWidth, cellHeight);
}

@end 